package org.gdpu.action;

import com.opensymphony.xwork2.ModelDriven;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.gdpu.model.BloodOrder;
import org.gdpu.service.BloodOrderService;
import org.gdpu.util.ChangeTime;
import org.gdpu.util.ExcelUtil;
import org.gdpu.vo.FileVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Component("file")
@Scope("prototype")
public class FileAction extends MyActionSupport implements ModelDriven<FileVO> {

    @Qualifier("excelUtil")
    @Autowired
    private ExcelUtil excelUtil;

    private final FileVO fileVO = new FileVO();
    private BloodOrderService bloodOrderService;
    private final static Logger logger = Logger.getLogger(FileAction.class);
    private List<BloodOrder> bos = new ArrayList<BloodOrder>();
    private static String SAVE_PATH_DIR = "d:/hospital/_file/_excel/";


    public String createExcelByBloodOrder() {

        // 得到备份文件的目录的真实路径
        File dir = new File(SAVE_PATH_DIR);
        // 如果该目录不存在，就创建
        if (!dir.exists()) {
            dir.mkdirs();
        }
        Date begin = setBeginDate(fileVO.getStartTime());
        Date end = setEndDate(fileVO.getEndTime());
        if(end.before(begin)){
            fileVO.setResultMessage("时间选择错误，请重新选择！");
            return ERROR;
        }
        bos = bloodOrderService.allBloodOrderByDate(begin,end);
        if (bos.size() <= 0) {
            fileVO.setResultMessage("从 " + fileVO.getStartTime() + " 到 " + fileVO.getEndTime() + " 时间内，未有记录信息！");
            return ERROR;
        }
        String date = ChangeTime.formatDate(ChangeTime.getCurrentDate());
        //使用于07以上的版本，03以下的可以修改参数
        excelUtil.exportExcelByPath(SAVE_PATH_DIR + "/" + date + ".xlsx",
                bos, BloodOrder.class, true, date + " 记录信息 ");
        excelUtil.print(SAVE_PATH_DIR + date + ".xlsx");
        fileVO.setResultMessage("成功备份记录信息文件！文件名为" + date);
        logger.trace("Admin backup room used records success,file name is " + date);
        return SUCCESS;
    }

    private Date setBeginDate(String time) {
        return ChangeTime.parseDate(time + " 00:00:00");
    }

    private Date setEndDate(String time) {
        return ChangeTime.parseDate(time + " 23:59:59");
    }

    @Resource(name = "bloodOrderServiceImpl")
    public void setBloodOrderService(BloodOrderService bloodOrderService) {
        this.bloodOrderService = bloodOrderService;
    }

    @Override
    public FileVO getModel() {
        return fileVO;
    }

}